package com.yourenbang.lingyun.transaction.web.service.impl.pay.withdraw.channel;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.TypeReference;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.pay.PayFromEnum;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.core.exception.SysBizException;
import com.yourenbang.lingyun.core.exception.UserBizException;
import com.yourenbang.lingyun.core.message.Result;
import com.yourenbang.lingyun.core.util.DingdingUtils;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.http.HttpClientUtil;
import com.yourenbang.lingyun.core.util.json.JsonUtils;
import com.yourenbang.lingyun.transaction.config.DingdingConfig;
import com.yourenbang.lingyun.transaction.exception.WichdrawFailException;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundAccountWithdrawPaymentMapper;
import com.yourenbang.lingyun.transaction.util.yunhuisuan.DefaultResult;
import com.yourenbang.lingyun.transaction.util.yunhuisuan.RSAPKCS8Encrypt;
import com.yourenbang.lingyun.transaction.util.yunhuisuan.ResponseResult;
import com.yourenbang.lingyun.transaction.util.yunhuisuan.YunhuisuanUtil;
import com.yourenbang.lingyun.transaction.web.domain.dto.pay.linghuisuan.LinghuisuanAgentpayQueryDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.pay.yunhuisuan.YhsCallbackDto;
import com.yourenbang.lingyun.transaction.web.domain.dto.pay.yunhuisuan.YunhuisuanAgentpayDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.pay.yunhuisuan.YunhuisuanAgentpayParamDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.pay.yunhuisuan.YunhuisuanPaymentNoticeDTO;
import com.yourenbang.lingyun.transaction.web.domain.po.FundAccountWithdrawPayment;
import com.yourenbang.lingyun.transaction.web.domain.vo.pay.hjtx.AgentpayVO;
import com.yourenbang.lingyun.transaction.web.domain.vo.pay.yunhuisuan.BalanceRequestData;
import com.yourenbang.lingyun.transaction.web.domain.vo.pay.yunhuisuan.BalanceResponseData;
import com.yourenbang.lingyun.transaction.web.domain.vo.pay.yunhuisuan.PayRequestData;
import com.yourenbang.lingyun.transaction.web.domain.vo.pay.yunhuisuan.PayResponseData;
import com.yourenbang.lingyun.transaction.web.service.impl.pay.PayTypeApiServiceImpl;
import com.yourenbang.lingyun.transaction.web.service.pay.withdraw.channel.YunHuiSuanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;


@Slf4j
@Lazy
@Service("yunHuiSuanService")
public class YunHuiSuanServiceImpl implements YunHuiSuanService {

    @Autowired
    private DingdingConfig dingdingConfig;

    @Autowired
    private TransactionFundAccountWithdrawPaymentMapper fundAccountWithdrawPaymentMapper;

    @Autowired
    private javax.validation.Validator validator;

    private static YunhuisuanAgentpayParamDTO yunhuisuanAgentpayParamDTO;


    public YunHuiSuanServiceImpl(PayTypeApiServiceImpl payTypeApiService) {
        try {

            Map<String, String> typeParams = payTypeApiService.getPayParams(PayTypeEnum.YUNHUISUAN, PayFromEnum.yxy_withdraw_ally_all);

            yunhuisuanAgentpayParamDTO = JsonUtils.convertValue(typeParams, YunhuisuanAgentpayParamDTO.class);

            log.info("【云会算代付】支付渠道参数:{}", JSON.toJSONString(yunhuisuanAgentpayParamDTO));

        } catch (Exception e) {

            log.error(e.getMessage() + PayTypeEnum.YUNHUISUAN.getCode() + PayFromEnum.yxy_withdraw_ally_all.getCode(), e);
        }

    }

    /**
     * 代付
     */
    @Override
    public AgentpayVO agentpay(YunhuisuanAgentpayDTO yunhuisuanAgentpayDTO) {

        Set<ConstraintViolation<YunhuisuanAgentpayDTO>> validates = validator.validate(yunhuisuanAgentpayDTO);
        if (!validates.isEmpty()) {
            for (ConstraintViolation<YunhuisuanAgentpayDTO> violation : validates) {
                KLog.error("校验失败: {}", violation.getPropertyPath(), violation.getMessage());
            }
            throw new UserBizException(BizCodeMessages.PARAMS_ERROR);
        }


        //检查代付有效性
        if (!checkPayValidate(yunhuisuanAgentpayDTO.getAmt())) {
            throw new WichdrawFailException("云会算余额不足");
        }

        //构造代付请求参数
        PayRequestData payRequestData = buildRequestParams(yunhuisuanAgentpayDTO);

        //发起代付
        return sendPayment(payRequestData);

    }

    /**
     * 代付查询
     * 如已代付成功
     */
    @Override
    public boolean checkAgentpayResult(LinghuisuanAgentpayQueryDTO dto) {

//        QryPaymentResultReq req = new QryPaymentResultReq();
//        req.setOutBatchNo(dto.getOutOrderNo());
//        ResponseResult<PaymentResultResp> responseResult;
//        try {
//            responseResult = PaymentApi.queryPaymentResult(req);
//        } catch (Exception ex) {
//            KLog.warn("【代付查询】请求失败:{},入参:{}", ex.getMessage(), dto.toJSON());
//            throw new WichdrawWaitException(ex.getMessage());
//        }
//
//        if (responseResult.getCode() != LinghuisuanUtil.CODE_SUCCESS) {
//            return false;
//        }
//
//        PaymentResultResp paymentResultResp = ResponseUtil.getData(responseResult);
//
//        return paymentResultResp.getStatus().compareTo(LinghuisuanUtil.PAY_NOTICE_STATUS_SUCCESS) == 0;
        return true;
    }

    private YunhuisuanPaymentNoticeDTO parseNoticeParams(String requestBody) {

        YhsCallbackDto yhsRepayCallbackDto = JSONUtil.toBean(requestBody, YhsCallbackDto.class);

        //json字符顺序保持一致
        String body = JSONUtil.toJsonStr(yhsRepayCallbackDto.getBody());
        String sign = yhsRepayCallbackDto.getSign();
        YunhuisuanPaymentNoticeDTO yunhuisuanPaymentNoticeDTO = yhsRepayCallbackDto.getBody();
        try {

            //修改自己的企业的公钥
            String publicKey = yunhuisuanAgentpayParamDTO.getPlatPublickey();
            RSAPublicKey pubKey = RSAPKCS8Encrypt.loadPublicKey(publicKey);

            if (!RSAPKCS8Encrypt.doCheck(body, sign, pubKey)) {

                KLog.error("验签不通过");
                return null;

            }

            return yunhuisuanPaymentNoticeDTO;

        } catch (Exception e) {
            KLog.error("云汇算解析失败,{}", e.getMessage());
        }

        return null;

    }

    /**
     * 提现回调
     */
    @Override
    public Result<FundAccountWithdrawPayment> withdrawNotice(String requestBody) {

        YunhuisuanPaymentNoticeDTO yunhuisuanPaymentNoticeDTO = parseNoticeParams(requestBody);
        if (Objects.isNull(yunhuisuanPaymentNoticeDTO)) {
            return Result.builder().fail(BizCodeMessages.TRANSACTION_SIGN_CHECK_FAIL, "解析参数失败");
        }

        String orderSn = yunhuisuanPaymentNoticeDTO.getEntOrderNo();
        Short platNo = PlatNoEnums.YXY.getCode();

        FundAccountWithdrawPayment payment = fundAccountWithdrawPaymentMapper.findByOrderSn(PlatNoEnums.YXY.getCode(), orderSn);

        if (Objects.isNull(payment)) {

            KLog.error("【提现回调】未找到提现订单,入参:{}", yunhuisuanPaymentNoticeDTO);
            return Result.builder().fail(BizCodeMessages.ORDER_NO_EXISTS);
        }
        payment.setPlatNo(platNo);

        if (YunhuisuanUtil.PAYCALLBACK_STATUS_SUCCESS.equals(yunhuisuanPaymentNoticeDTO.getStatus())) {

            return Result.builder().success(payment);

        } else if (YunhuisuanUtil.PAYCALLBACK_STATUS_FAIL.equals(yunhuisuanPaymentNoticeDTO.getStatus())
                || YunhuisuanUtil.PAYCALLBACK_STATUS_REFUND_TICKET.equals(yunhuisuanPaymentNoticeDTO.getStatus())
                || YunhuisuanUtil.PAYCALLBACK_STATUS_REFUND_PAY.equals(yunhuisuanPaymentNoticeDTO.getStatus())
                || YunhuisuanUtil.PAYCALLBACK_STATUS_CANCEL.equals(yunhuisuanPaymentNoticeDTO.getStatus())
        ) {

            KLog.warn("【提现回调】提现失败,入参:{}", yunhuisuanPaymentNoticeDTO);
            Result<FundAccountWithdrawPayment> result = Result.builder().fail(BizCodeMessages.TRANSACTION_WITHDRAW_FAIL);
            result.setData(payment);

            return result;

        } else if (yunhuisuanPaymentNoticeDTO.getStatus().equals(YunhuisuanUtil.PAYCALLBACK_STATUS_PROCESS)
                || yunhuisuanPaymentNoticeDTO.getStatus().equals(YunhuisuanUtil.PAYCALLBACK_STATUS_WAIT)) {

            return Result.builder().fail(BizCodeMessages.TRANSACTION_WITHDRAW_PROCESS);

        }

        KLog.error("【提现回调】接口响应异常,入参:{}", yunhuisuanPaymentNoticeDTO);
        return Result.builder().fail(BizCodeMessages.UNKNOWN_ERROR, "接口响应异常");

    }

    /**
     * 签约回调(未实现)
     * 2023/12/20 目前云汇算免签约
     */
    @Override
    public void signNotice(String param) {
        KLog.error("回调异常,云汇算免签,不应有签约回调,{}", param);
        throw new SysBizException(BizCodeMessages.UNKNOWN_ERROR, "回调异常,云汇算免签,不应有签约回调");
//        KLog.info("【签约回调】入参:{}", param);
//
//        LinghuisuanSignNoticeDTO linghuisuanSignNoticeDTO = JsonUtils.readValue(param, LinghuisuanSignNoticeDTO.class);
//
//        MerchantPaymentSignExample merchantPaymentSignExample = new MerchantPaymentSignExample();
//        merchantPaymentSignExample.createCriteria()
//                .andSignChannelTypeEqualTo(LinghuisuanUtil.SIGN_CHANNEL_TYPE_LINGHUISUAN)
//                .andThirdIdEqualTo(linghuisuanSignNoticeDTO.getContractId());
//        List<MerchantPaymentSign> merchantPaymentSigns = merchantPaymentSignMapper.selectByExample(merchantPaymentSignExample);
//
//        if (CollectionUtils.isEmpty(merchantPaymentSigns)) {
//            KLog.warn("【签约回调】数据库签约信息不存在,无法更新签约状态,入参:{}", param);
//            return;
//        }
//
//        MerchantPaymentSign merchantPaymentSign = merchantPaymentSigns.get(0);
//        if (merchantPaymentSign.getSignState().compareTo(LinghuisuanUtil.SIGN_STATUS_DONE) != 0) {
//            KLog.warn("【签约回调】签约失败,忽略,入参:{}", param);
//            return;
//        }
//
//        //保存签约状态
//        merchantPaymentSign.setContractUrl(linghuisuanSignNoticeDTO.getContactUrl());
//        merchantPaymentSign.setSignState(LinghuisuanUtil.SIGN_STATUS_DONE);
//        merchantPaymentSign.setCallbackData(param);
//
//        int inSing = merchantPaymentSignMapper.updateByPrimaryKey(merchantPaymentSign);
//        BizAssertUtils.assertOne(inSing, "添加签约记录失败");

    }


    /**
     * 提现用户签约检查,目前未实现
     *
     * @param payFrom
     * @param userBaseId
     * @return success 检查成功,有值代表未签约,返回签约地址
     * fail 检查失败
     */
    @Override
    public Result<String> alreadySign(PayFromEnum payFrom, String userBaseId) {

        return Result.builder().success();

        //TODO 未实现签约,云汇算前期免签约,以下代码为 灵会算代码

//        UserBase userBase = userBaseMapper.selectByPrimaryKey(userBaseId);
//
//        if (ObjectUtils.isEmpty(userBase)) {
//            return Result.builder().fail();
//        }
//
//        if (StringUtils.isBlank(userBase.getIdNumber())) {
//            return Result.builder().fail();
//        }
//
//        MerchantPaymentSignExample merchantPaymentSignExample = new MerchantPaymentSignExample();
//        merchantPaymentSignExample.createCriteria()
//                .andSignChannelTypeEqualTo(LinghuisuanUtil.SIGN_CHANNEL_TYPE_LINGHUISUAN)
//                .andIdNumberEqualTo(userBase.getIdNumber())
//                .andUserBaseIdEqualTo(userBaseId);
//        List<MerchantPaymentSign> merchantPaymentSigns = merchantPaymentSignMapper.selectByExample(merchantPaymentSignExample);
//
//
//        if (CollectionUtils.isNotEmpty(merchantPaymentSigns)
//                && merchantPaymentSigns.get(0).getSignState().compareTo(LinghuisuanUtil.SIGN_STATUS_DONE) == 0) {
//            return Result.builder().success();
//        }
//
//        //如果数据库无签约,去远程获取签约状态
//        Result<ContractPreviewResp> result = getSignInfoFromRemote(userBase);
//        if (result.isFail()) {
//            throw new SysBizException(BizCodeMessages.UNKNOWN_ERROR, "获取用户签约状态失败," + result.getDesc());
//        }
//
//        ContractPreviewResp contractPreviewResp = result.getData();
//
//
//        saveMerchantSign(userBase, contractPreviewResp, merchantPaymentSigns);
//
//        //未签约,返签约地址
//        //TODO 临时关闭签约
//        if (false && !contractPreviewResp.isSigned()) {
//            return Result.builder().success(contractPreviewResp.getContractUrl());
//        }
//
//        //已签约,返回空
//        return Result.builder().success();
    }

//    /**
//     * 保存签约数据
//     */
//    private void saveMerchantSign(UserBase userBase, ContractPreviewResp contractPreviewResp,
//                                  List<MerchantPaymentSign> merchantPaymentSigns) {
//
//        if (CollectionUtils.isEmpty(merchantPaymentSigns)) {
//
//            MerchantPaymentSign merchantPaymentSign = new MerchantPaymentSign();
//            merchantPaymentSign.setSignChannelType(LinghuisuanUtil.SIGN_CHANNEL_TYPE_LINGHUISUAN);
//            merchantPaymentSign.setThirdId(contractPreviewResp.getContractId().toString());
//            merchantPaymentSign.setUserBaseId(userBase.getUserBaseId());
//            merchantPaymentSign.setIdNumber(userBase.getIdNumber());
//            merchantPaymentSign.setCallbackData(contractPreviewResp.toString());
//            merchantPaymentSign.setContractUrl(contractPreviewResp.getContractUrl());
//            merchantPaymentSign.setSignState(contractPreviewResp.isSigned() ? LinghuisuanUtil.SIGN_STATUS_DONE : LinghuisuanUtil.SIGN_STATUS_WAIT);
//
//            int inSing = merchantPaymentSignMapper.insertSelective(merchantPaymentSign);
//            BizAssertUtils.assertOne(inSing, "添加签约记录失败");
//
//        } else {
//
//            MerchantPaymentSign merchantPaymentSign = new MerchantPaymentSign();
//            merchantPaymentSign.setThirdId(contractPreviewResp.getContractId().toString());
//            merchantPaymentSign.setContractUrl(contractPreviewResp.getContractUrl());
//            merchantPaymentSign.setSignState(contractPreviewResp.isSigned() ? LinghuisuanUtil.SIGN_STATUS_DONE : LinghuisuanUtil.SIGN_STATUS_WAIT);
//
//            merchantPaymentSign.setMerchantPaymentSignId(merchantPaymentSigns.get(0).getMerchantPaymentSignId());
//            int inSing = merchantPaymentSignMapper.updateByPrimaryKeySelective(merchantPaymentSign);
//            BizAssertUtils.assertOne(inSing, "更新签约记录失败");
//        }
//
//    }

    /**
     * 云汇算平台代付余额查询,单位元
     *
     * @return 返回代付余额, 返回null表示查询余额失败
     */
    @Override
    public BigDecimal getBalance() {

        ResponseResult<BalanceResponseData> responseResult = null;
        BalanceResponseData balanceResponseData = null;

        BalanceRequestData balanceRequestData = new BalanceRequestData();
        balanceRequestData.setTimestamp(String.valueOf(System.currentTimeMillis()));
        balanceRequestData.setAccountType("100");

        try {

            //提交代付请求,返回处理中,是否成功需要通过查询或者回调获得
            responseResult = post(YunhuisuanUtil.APICODE_BALANCE, balanceRequestData, new TypeReference<BalanceResponseData>() {
            });

            if (Objects.isNull(responseResult)) {
                return null;
            }

            balanceResponseData = responseResult.getData();

        } catch (Exception e) {

            return null;

        }

        if (ObjectUtils.isNotEmpty(responseResult) && responseResult.isSuccess()) {
            //获得余额,并且单位分转为元
            return BigDecimal.valueOf(Integer.parseInt(balanceResponseData.getUsableAmt()))
                    .divide(BigDecimal.valueOf(100));
        }

        return null;

    }


    private boolean checkPayValidate(BigDecimal needPayMoney) {

        //代付渠道余额检查
        BigDecimal balance = getBalance();
        if (Objects.isNull(balance)) {
            throw new WichdrawFailException("获取代付余额失败");
        }

        if (needPayMoney.compareTo(balance.multiply(new BigDecimal(100))) > 0) {

            String msg = "【账户余额不足预警】友仁帮-云会算账户仅剩[" + balance + "]元,请尽快充值!已关闭支付渠道";
            DingdingUtils.sendToDingding(msg, dingdingConfig.getDingdingWarnToken());
            DingdingUtils.sendToDingding(msg, dingdingConfig.getDingdingPushYjgtToken());
            return false;
        }

        return true;
    }

    private PayRequestData buildRequestParams(YunhuisuanAgentpayDTO yunhuisuanAgentpayDTO) {

        String outOrderNO = yunhuisuanAgentpayDTO.getOrderNo();
        String remark = StringUtils.isBlank(yunhuisuanAgentpayDTO.getRemark()) ? "收益" : yunhuisuanAgentpayDTO.getRemark();


        PayRequestData payRequestData = new PayRequestData();
        payRequestData.setTimestamp(String.valueOf(System.currentTimeMillis()));
        payRequestData.setTaskNo(yunhuisuanAgentpayParamDTO.getTaskNo());
        payRequestData.setEntOrderNo(outOrderNO);
        payRequestData.setPayeeName(yunhuisuanAgentpayDTO.getAccountName());
        payRequestData.setPayeeIdCard(yunhuisuanAgentpayDTO.getIdCard());
        payRequestData.setPayeePhone(yunhuisuanAgentpayDTO.getPhone());
        payRequestData.setPayeeAccount(yunhuisuanAgentpayDTO.getAccountNo());
        payRequestData.setAmount(String.valueOf(yunhuisuanAgentpayDTO.getAmt()));
        payRequestData.setPaymentModel("100");
        payRequestData.setCallbackUrl(yunhuisuanAgentpayParamDTO.getAgentpaycallurl());
        payRequestData.setRemark(remark);

        return payRequestData;

    }


    /**
     * 发起代付
     *
     * @param payRequestData
     * @return 支付响应信息
     */
    private AgentpayVO sendPayment(PayRequestData payRequestData) {

        ResponseResult<PayResponseData> responseResult = null;

        try {

            //提交代付请求,返回处理中,是否成功需要通过查询或者回调获得
            responseResult = post(YunhuisuanUtil.APICODE_PAY, payRequestData, new TypeReference<PayResponseData>() {
            });

        } catch (Exception e) {

            throw new SysBizException(BizCodeMessages.UNKNOWN_ERROR, e.getMessage());

        } finally {

            KLog.info("【云会算代付】接口响应:{},入参:{}", responseResult, payRequestData);

        }

        if (Objects.isNull(responseResult)) {
            throw new SysBizException(BizCodeMessages.UNKNOWN_ERROR, responseResult.getMsg());
        }

        if (!responseResult.isSuccess()) {
            // 代付为异步处理,返回不成功,一定失败,返回成功,需要根据异步结果判断是否成功
            // 明确支付已失败,需退还用户资金
            throw new WichdrawFailException("支付失败," + responseResult.getMsg());

        }

        PayResponseData payResponseData = responseResult.getData();


        AgentpayVO vo = new AgentpayVO();
        vo.setCode(responseResult.getCode());
        vo.setMessage(responseResult.getMsg());
        vo.setOrderNo(payRequestData.getEntOrderNo());
        vo.setSerialNumber(payResponseData.getPfOrderNo());

        return vo;

    }


    private <T> ResponseResult<T> post(String apiCode, Object requestData, TypeReference<T> type) {

        String body = JSONUtil.toJsonStr(requestData);
        KLog.info("加密前body报文:{}", body);
        RSAPublicKey pubKey;
        String bodyText;

        try {

            pubKey = RSAPKCS8Encrypt.loadPublicKey(yunhuisuanAgentpayParamDTO.getPlatPublickey());
            bodyText = RSAPKCS8Encrypt.encrypt(pubKey, body.getBytes(StandardCharsets.UTF_8));

        } catch (Exception e) {
            KLog.error(BizCodeMessages.UNKNOWN_ERROR);
            return null;
        }


        Map<String, Object> jsonParam = new HashMap<>(3);
        jsonParam.put("enterpriseNo", yunhuisuanAgentpayParamDTO.getEnterpriseNo());
        jsonParam.put("channelNo", yunhuisuanAgentpayParamDTO.getChannelNo());
        jsonParam.put("apiCode", apiCode);
        jsonParam.put("body", bodyText);
        jsonParam.put("version", yunhuisuanAgentpayParamDTO.getVersion());
        KLog.info("加密前报文:{}", JSONUtil.toJsonStr(jsonParam));

        try {

            String response = HttpClientUtil.httpPostRequest(yunhuisuanAgentpayParamDTO.getAgentpayurl(),
                    JSONUtil.toJsonStr(jsonParam));
//{"code":"000000","msg":"成功","data":{"entOrderNo":"ENT1703148367079","pfOrderNo":"1737756321079316480","applyTime":"2023-12-21 16:46:07"},"sign":"hhAwKxkc8DtY+luCjXcvCCCeb/ltFx5QjTW7PDJpHE1mU28xtYihZUp251b6WTIKtEfaEdMyeT6qQyTnqGeAb0Aq339SK+Hj6/9FlyokWJ+hcJsDh2acRS0sOn0rURu9tERs81Qt5O9pMHWcSsRz4ozX68QDNwZXBdv64Z0h9mp/zcS2s4urI6k7AZePqaTa5uPKD7dIkZn1iwtDBB3LfvD5wKedyyAAh6k4nKOq6/W3YE0s0obBEaDtL5Uk8LS1HTq1vGUmwF485jxYqOXyf73/KYNKL1BbNOLXTKGrkKk7MOsPRcKu/efYupTIv/sic6PIiLM/yonAr294RdQYsw=="}
            KLog.info("返回报文内容:{}", response);

            if (ObjectUtils.isEmpty(response)) {
                KLog.error("代付响应为空");
                return null;
            }

            JSONObject jsonObject = JSONUtil.parseObj(response, false);
            String sign = jsonObject.getStr("sign");
            String data = jsonObject.getStr("data");

            DefaultResult defaultResult = com.alibaba.fastjson.JSON.parseObject(response, DefaultResult.class);
            ResponseResult responseResult = new ResponseResult<>(defaultResult.getCode(), defaultResult.getMsg());

            if (StringUtils.isNotEmpty(defaultResult.getData())
                    && defaultResult.isSuccess()
                    && Objects.nonNull(type)) {

                responseResult.setData(com.alibaba.fastjson.JSON.parseObject(defaultResult.getData(), type));
            }

            if (defaultResult.getCode().equals(YunhuisuanUtil.APICODE_IP_LIMIT)) {
                KLog.error(BizCodeMessages.TRANSACTION_WITHDRAW_FAIL, "代付请求时IP受限");
                return responseResult;
            }

            if (ObjectUtils.isNotEmpty(data) && !RSAPKCS8Encrypt.doCheck(data, sign, pubKey)) {
                if (responseResult.isSuccess()) {
                    //处理成功,但验签失败,可能支付成功,不能回滚
                    KLog.error(BizCodeMessages.TRANSACTION_SIGN_CHECK_FAIL, "验签失败");
                } else {
                    KLog.error(BizCodeMessages.UNKNOWN_ERROR, "验签失败");
                    return null;
                }
            }

            return responseResult;

        } catch (Exception e) {
            KLog.error(BizCodeMessages.UNKNOWN_ERROR, e);
        }


        return null;

    }

}
